#!/usr/bin/env perl
#
#	Analyse a package list file produced by dbaudit
#
#	Stuart Crook, 21/3/09
#

sub usage {
	print "dbstats: Print statistics from a dbaudit package list\n";
	print "  dbstats -f package_list [-m] [-u]\n";
	print "    -f package_list  The package list to analyse\n";
	print "    -m               Print a list of packages without binary roots\n";
	print "    -u               Print a list of unresolved dependencies\n";
}

#
#	If $_[0] isn't already in @unres, add it
#
sub adddep {
	foreach $un (@unres) {
		if($un eq $_[0]) { return; }
	}
	push(unres, $_[0]);
}

#
#	Start of program proper
#
if($#ARGV < 1) {
	usage();
	exit;
}

for( $i = 0; $i <= $#ARGV; $i++ ) {

	if($ARGV[$i] eq '-f') {
		#	set the path to the package_list file
		if($#ARGV == $i++) {
			usage();
			exit;
		}
		$pkglist = $ARGV[$i];

	} elsif($ARGV[$i] eq '-m') {
		# set the flag to have missing binary roots listed
		$m = 1;

	} elsif($ARGV[$i] eq '-u') {
		# set the flag to have unresolved dependencies listed
		$u = 1;
	}

}

#
#	Check and open the package list
#
if($pkglist eq '') {
	usage();
	exit;
}

open(LST, $pkglist) || die "Couldn't open file $pkglist\n";

#
#	Work through the package list. We will:
#		- count pakages into $count
#		- put missing packages into @missing
#		- put unresloved links into @unres
#
while($line = <LST>) {
	if($line =~ /^(\S+) (Y|N) /) {

		$count++;

		#if($count > 10) { next; }

		if( $2 eq 'N' ) {
			push(missing, $1);
		} else {
			$' =~ /{ (.*) }/;
			if($1 ne '') {
				@deps = split(' ', $1);
				foreach $dep (@deps) { 
					if($dep =~ m|^/|) { adddep($dep); }
				}
			}
		}
 
	}
}

close(LST);

#
#	Show the relevant statistics
#
$mcount = @missing;
$ucount = @unres;
print "$count packages, $mcount missing binary roots, $ucount unresolved dependencies\n";

if(($m == 1) && ($mcount != 0)) {
	@missing = (sort @missing);
	print "  Packages missing binary roots:\n";
	foreach $pkg (@missing) {
		print "    $pkg\n";
	}
}

if(($u == 1) && ($ucount != 0)) {
	@unres = (sort @unres);
	print "  Unresolved dependencies:\n";
	foreach $pkg (@unres) {
		print "    $pkg\n";
	}
}

